<template>
  <div class="corp-form cardStyle">
    <el-row :gutter="24">
      <el-col :lg="24" :md="24" :sm="24" :span="24" :xl="24" :xs="24">
        <el-scrollbar height="83vh">
          <!-- 公司信息管理 -->
          <vab-card class="cardTitle">
            <div class="flex_sb">
              <div class="flex">
                <p class="leve_title">客户{{ route.query.type == 2 || route.query.type == 3 ? '更新':route.query.type == 4?'详情':'新建'}}</p>
<!--                <p>{{ customerStores.storage }}</p>-->
              </div>
              <div class="flex">
                <el-button
                  v-if="route.query.type != 4  && customerStatus == 0 || customerStatus == -1 "
                  class="customerButton1"
                  :loading="staging"
                  @click="storage"
                >
                  暂存
                </el-button>
                <el-button :loading="staging" @click="cancel">{{route.query.type != 4 ? '取消' : '返回' }}</el-button>
                <!--                <el-popconfirm
                  :title="'取消后 表单内容不会保持 是否要继续'"
                  @confirm="cancellation"
                >
                  <template #reference>

                  </template>
                </el-popconfirm>-->
                <el-button
                  v-if="route.query.type != 4"
                  :loading="staging"
                  type="primary"
                  @click="handleClick(son)"
                >
                  提交
                </el-button>
              </div>
            </div>
          </vab-card>
          <!--          <el-scrollbar height="calc(83vh - 100px)">-->
          <el-form
            :class="route.query.type == 4?'form_node':'form_node1'"
            ref="form"
            :disabled = 'route.query.type == 4'
            label-position="right"
            label-width="135px"
            :model="base_formData"
          >
            <!-- 基础信息 -->
            <AddBaseMode  ref="son" v-if="addLoading" v-model:base_formDatas="base_formData" v-model:rules="rules" />
            <!-- 发票信息 -->
            <AddInvoiceMode v-if="addLoading" v-model:base_formDatas="base_formData.invoice"/>
            <!-- 银行信息 -->
            <AddBankMode v-if="addLoading" v-model:base_formDatas="base_formData.bank" v-model:bank_ref = "bank_ref" />
            <!-- 收货地址信息 -->
            <AddRessMode v-if="addLoading" v-model:base_formDatas="base_formData.location" />
          </el-form>
          <!--          </el-scrollbar>-->
        </el-scrollbar>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>

  defineOptions({
    name: 'AddCustomers',
  })
  import {customer_info, customer_insert, customer_update} from '/@/api/dms/customer'
  import customerStore from './storeList'
  import router from '/@/router'
  import {ElMessage, FormRules} from 'element-plus'
  import AddBaseMode from './component/AddBaseMode.vue'
  import AddInvoiceMode from './component/AddInvoiceMode.vue'
  import AddBankMode from './component/AddBankMode.vue'
  import AddRessMode from './component/AddRessMode.vue'
  const pintStoreList = customerStore()
  // 状态
  const customerStatus = ref<any>(-1)
  // 变量
  const form = ref(null)
  const isUpdate = ref<boolean>(true)
  const route:any = useRoute() //route.query.id
const staging = ref(false)
const addLoading = ref(false)
  const son = ref(null)
const bank_ref = reactive([])
  // 基础信息
  let base_formData = reactive<any>({
    name: '',
    short_name: '',
    number: '',
    create_org_name: '',
    use_org_id: '',
    is_used: 1,
    is_group: 0,
    group_cust_id: '',
    cust_type_id: '',
    cust_type_name: '',
    primary_group: '',
    create_name: '',
    create_date: '',
    trading_curr_id: '1',
    trading_curr_name: '人民币',
    settle_type_id: '',
    group_item:'',
    invoice_type: '1',
    invoice_type_name: '增值税专用发票',
    price_list_id: '1',
    price_list_name: '价目表1',
    is_credit_check: 1,
    payer: '',
    contact: '',
    position: '',
    tel: '',
    primary_group_name:'',
    invoice: [
      {
        id: 1,
        invoice_title: '',
        tax_register_code: '',
        invoice_bank_name: '',
        invoice_bank_account: '',
        invoice_tel: '',
        invoice_address: '',
        socialcre_code: '',
      },
    ],
    bank: [
      {
        id: 1,
        country: '',
        account_name: '',
        invoice_bank_account: '',
      },
    ],
    location: [
      {
        id: 1,
        address_code:'',
        shipping_contact: '',
        shipping_tel: '',
        shipping_address: '',
        address: '',
        is_default_consignee: 0,
      },
    ],
  })
  const rules = ref<FormRules<any>>({
    name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
    is_used: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
    ],
    is_group: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
    ],
    price_list_id: [
      {
        required: true,
        message: '请选择价目表',
        trigger: 'change',
      },
    ],
    is_credit_check: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
    ],
    contact: [
      {
        required: true,
        message: '请输入联系人名称',
        trigger: 'blur',
      },
    ],
    tel: [{ required: true, message: '请输入手机号码', trigger: 'blur' },],
    payer: [
      {
        required: true,
        message: '请选择付款方式',
        trigger: 'change',
      },
    ],
  })
  // 判断跳转
/*  watchEffect(()=>{
    if( !route.query.type){
      router.push('/customer/queryCustomer')
    }
  })*/
  // 获取
  //取消事件
  const cancellation = () => {
    router.push('/customer/queryCustomer')
  }
  onMounted(async ()=>{
    if (route.query.id != 0) {
      customer_info({ uid: route.query.id }).then((data: any) => {
        if (data.code == 200) {
          addLoading.value=true
          customerStatus.value =  data.data.status
          if(route.query.type == 1){
            base_formData = { ...data.data,number:'',create_name:'',create_date:'',location:data.data.location.length > 0 ? data.data.location : [
                {
                  id: 1,
                  address_code:'',
                  shipping_contact: '',
                  shipping_tel: '',
                  shipping_address: '',
                  address: '',
                  is_default_consignee: 0,
                },
              ],invoice:data.data.invoice.length > 0 ? data.data.invoice : [
                {
                  id: 1,
                  invoice_title: '',
                  tax_register_code: '',
                  invoice_bank_name: '',
                  invoice_bank_account: '',
                  invoice_tel: '',
                  invoice_address: '',
                  socialcre_code: '',
                },
              ],bank:data.data.bank.length > 0 ? data.data.bank : [
                {
                  id: 1,
                  country: '',
                  account_name: '',
                  invoice_bank_account: '',
                },
              ]}
          }else {
            base_formData = { ...data.data,location:data.data.location.length > 0 ? data.data.location : [
                {
                  id: 1,
                  address_code:'',
                  shipping_contact: '',
                  shipping_tel: '',
                  shipping_address: '',
                  address: '',
                  is_default_consignee: 0,
                },
              ],invoice:data.data.invoice.length > 0 ? data.data.invoice : [
                {
                  id: 1,
                  invoice_title: '',
                  tax_register_code: '',
                  invoice_bank_name: '',
                  invoice_bank_account: '',
                  invoice_tel: '',
                  invoice_address: '',
                  socialcre_code: '',
                },
              ],bank:data.data.bank.length > 0 ? data.data.bank : [
                {
                  id: 1,
                  country: '',
                  account_name: '',
                  invoice_bank_account: '',
                },
              ]}
          }
        }
      })
    }else {
      addLoading.value=true
    }
  })
  const add_insert = async (data: any) => {
    customer_insert({ ...data,status:1 })
      .then((data: any) => {
        staging.value=false
        router.push('/customer/queryCustomer')
        ElMessage({
          message: '新建成功',
          type: 'success',
        })
      })
      .catch(() => {
        staging.value=false
        ElMessage({
          message: '新建失败',
          type: 'error',
        })
      })
  }
 const storage_insert = async (data: any) => {
   customer_insert({ ...data,status:0 })
     .then((data: any) => {
       staging.value=false
       router.push('/customer/queryCustomer')
       ElMessage({
         message: '暂存成功',
         type: 'success',
       })
     })
     .catch(() => {
       staging.value=false
       ElMessage({
         message: '暂存失败',
         type: 'error',
       })
     })
 }
  const update_insert = async (data: any) => {
    customer_update({uid:route.query.id,customer:{...data,status:1}})
      .then((data: any) => {
        staging.value=false
        router.push('/customer/queryCustomer')
        ElMessage({
          message: '更新成功',
          type: 'success',
        })
      })
      .catch(() => {
        staging.value=false
        ElMessage({
          message: '更新失败',
          type: 'error',
        })
      })
  }
  // 发票表单验证方法
  const checking_invoice =(formData:any)=>{
    //电话
    const phone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/
    // 统一信用代码
    const code = /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{15})$/
    // 银行账号
    const bank_code = /^\d{9,18}$/
  const phone_1:any = formData.invoice.map((value:any, index:number)=>{
      if( value.invoice_tel == ''? true : phone.test(value.invoice_tel)){
         return true
      }else {
        ElMessage.warning(`发票信息${index == 0 ? ' ' : index}开票联系电话错误，请输入正确开票联系电话`)
        return false
      }
    })
    const phone_2:any = formData.invoice.map((value:any, index:number)=>{
      if( value.socialcre_code == ''? true : code.test(value.socialcre_code)){
        return true
      }else {
        ElMessage.warning(`发票信息${index == 0 ? ' ' : index}统一社会信用代码错误，请输入正确统一社会信用代码`)
        return false
      }
    }) //invoice_bank_account
    const phone_3:any = formData.invoice.map((value:any, index:number)=>{
      if( value.invoice_bank_account == ''? true : bank_code.test(value.invoice_bank_account)){
        return true
      }else {
        ElMessage.warning(`发票信息${index == 0 ? ' ' : index}银行账号错误，请输入正确银行账号`)
        return false
      }
    })
    const check = [...phone_1,...phone_2,...phone_3].every(i=>i==true)
    return check
  }
  // 银行信息表单验证方法
  const checking_bank =(formData:any)=>{
    //电话
    const phone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/
    // 统一信用代码
    const code = /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{15})$/
    // 银行账号
    const bank_code = /^\d{9,18}$/
    const phone_1:any = formData.bank.map((value:any, index:number)=>{
      if( value.invoice_bank_account == ''? true : bank_code.test(value.invoice_bank_account)){
        return true
      }else {
        ElMessage.warning(`银行信息${index == 0 ? ' ' : index}银行账号错误，请输入正确银行账号`)
        return false
      }
    })
    const check = [...phone_1].every(i=>i==true)
    return check
  }
  // 收货地址信息信息表单验证方法
  const checking_location =(formData:any)=>{
    //电话
    const phone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/
    // 统一信用代码
    const code = /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{15})$/
    // 银行账号
    const bank_code = /^\d{9,18}$/
    const phone_1:any = formData.location.map((value:any, index:number)=>{
      if( value.shipping_tel == ''? true : phone.test(value.shipping_tel)){
        return true
      }else {
        ElMessage.warning(`收货地址信息${index == 0 ? ' ' : index}联系电话错误，请输入正确联系电话`)
        return false
      }
    })
    const check = [...phone_1].every(i=>i==true)
    return check
  }
  // 点击事件
  const handleClick = async (value: any) => {
      staging.value=true
   /* const sumb1 = checking_invoice(base_formData)
    const sumb2 = checking_bank(base_formData)
    const sumb3 = checking_location(base_formData)
      await value.validate((valid: any, fields: any) => {
        if(sumb1 && sumb2 && sumb3) {
          if (valid) {
            if (route.query.id != 0) {
              if (route.query.type == 1) {
                add_insert(base_formData)
              } else {
                update_insert(base_formData)
              }
            } else if (route.query.id == 0) {
              add_insert(base_formData)
            }
          } else {
            staging.value = false
          }
        }else {
          staging.value = false
        }
      })*/
    await value.form_date.validate((valid: any, fields: any) => {
      if (valid) {
        if (route.query.id != 0) {
          if (route.query.type == 1) {
            add_insert(base_formData)
          } else {
            update_insert(base_formData)
          }
        } else if (route.query.id == 0) {
          add_insert(base_formData)
        }
      } else {
        staging.value = false
      }
    })
  }
  const cancel = () => {
    router.push('/customer/queryCustomer')
  }
  //暂存
  const storage = ()=>{
    if(base_formData.name.trim() != ''){
      if(customerStatus.value && customerStatus.value == 0){
        customer_update({uid:route.query.id,customer:{...base_formData,status:0}})
          .then((data: any) => {
            staging.value=false
            router.push('/customer/queryCustomer')
            ElMessage({
              message: '暂存成功',
              type: 'success',
            })
          })
          .catch(() => {
            staging.value=false
            ElMessage({
              message: '暂存失败',
              type: 'error',
            })
          })
      }else {
        storage_insert(base_formData)
      }

    }else {
      ElMessage({
        message: '暂存时客户名称必填',
        type: 'error',
      })
    }
  }
</script>
<style lang="scss" scoped>
  @import './index.scss';
</style>
